const connection = require("../app/database");


class Service {
 async create(user){
    const { name, password } = user;
    console.log( name, password);
    const sql =`INSERT INTO users (name, password) VALUES (?,?)`;
    const result = await connection.execute(sql,[name, password] );
    console.log(result);
    return result[0];
  }
  async getUserByName(name){
    const sql = `SELECT * FROM users WHERE name = ?`; //? = name
    const result = await connection.execute(sql,[name] );
    return result[0];
  }
  async getAvatarInfo(userId){
    try {
      const sql = `SELECT * FROM avatar WHERE user_id = ?`;
      const [result] = await connection.execute(sql, [userId]);
      //获取最新的一条数据
      return result[result.length - 1];
    } catch (e) {
      console.log(e);
      return e;
    }
  }
  //将头像信息插入user数据库
  async updateAvatar(userId, avatarUrl){
try {
  const sql = `UPDATE users SET avatar_url = ? WHERE id = ?`;
  console.log(userId, avatarUrl);
  const result = await connection.execute(sql,[ avatarUrl,userId] );
  return result[0];
}catch (e) {
  console.log(e);
  return e;
}
  }
}

module.exports = new Service();